/* eslint-disable linebreak-style */
import React, { PureComponent } from 'react';
import {DatePicker, Form, Col, Row, Button, Table, message, Collapse, Checkbox, Popconfirm} from 'antd';
import { connect } from 'dva';
import moment from 'moment';
import PropTypes from 'prop-types';
import {getDicByKey, getToken} from "@/utils/common";
import Ellipsis from "@/components/Ellipsis";

const FormItem = Form.Item;
const { RangePicker } = DatePicker;


const { Panel } = Collapse;
const CheckboxGroup = Checkbox.Group;

@connect(state => ({
  currentUser: state.user.currentUser,
}))
// @Form.create()
export default class VehicleStatusListTable extends PureComponent {
  static contextTypes = {
    dicData: PropTypes.array,
  };
  state = {
    list: [],
    pagination: '',
    loading: false,
    formValues: '',
    pageRangeData: [],

    plainOptions:[],
    plainOptions_code:[],
    checkedList: ['ngtpCreateTime','lfPressureWarnning','rfPressureWarnning','lrPressureWarnning','rrPressureWarnning',
      'lfTpms','rfTpms','lrTpms','rrTpms','teau','seatBeltMaster','seatBeltSlave','autonomie','avgFuelConsumed','eachMileage'],    // 选中的checkbox

    columns:[],
    expButtonLoading: false,
    len : 1,//动态列数，动态可配置
    line_num : 1,//导出行数，动态可配置
    expire : 600 //导出时间间隔10分钟，动态可配置

  };

  componentWillMount() {
    const len = getDicByKey(this.context.dicData, `wl_export_param`, 'wl_ep_1');
    const line_num = getDicByKey(this.context.dicData, `wl_export_param`, 'wl_ep_2');
    const expire = getDicByKey(this.context.dicData, `wl_export_param`, 'wl_ep_3');
    const { dispatch, vin } = this.props;
    if (vin) {
      let obj = {};
      obj.vin = vin;
      obj.startDate = `${moment().format('YYYY-MM-DD')} 00:00:00`;
      obj.endDate = `${moment().format('YYYY-MM-DD')} 23:59:59`;
      obj.pageRangeData = [];
      this.setState({
        loading: true,
      });
      dispatch({
        type: 'extendForm/fetch',
        payload: {url:'/vehicle/getExportFields'},
        callback: (response) => {
          if (response.statusCode === '0') {
            let cols=[];
            for(let i=0;i<response.data.keys.length;i++){
              cols.push({
                title: response.data.values[i],
                dataIndex: response.data.keys[i],
              },)
            }
            this.setState({
              plainOptions_code : response.data.keys,
              plainOptions : response.data.values,
              columns : cols
            });
          } else {
            message.error(response.statusMessage);
          }
        },
      });

      dispatch({
        type: 'vehicle/getVehicleInstrument',
        payload: obj,
        callback: (response) => {
          if (response) {
            if (response.code && response.code === '500') {
              message.error(response.description);
            }
            if (response.statusCode && response.statusCode !== '0') {
              message.error(response.statusMessage);
            }
            this.setState({
              list: response.data && response.data.list  ? response.data.list : [],
              pagination: response.data && response.data.pagination  ? response.data.pagination : '',
              pageRangeData:  response.data && response.data.pageRange  ? response.data.pageRange : [],
            })
          }
          this.setState({
            loading: false,
            len : parseInt(len),
            line_num : parseInt(line_num),
            expire : parseInt(expire)
          })
        },
      });
    } else {
      message.error('服务器忙，请稍后再试！');
    }

  }
  componentDidMount() {
    // this.props.onRef(this);
  }

  setStateData = (data) =>{
    this.setState({
      ...data,
    })

  };


  handleSearch = (e) => {
    e.preventDefault();
    const { form, dispatch, vin } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const obj = fieldsValue;
      obj.vin = vin;
      obj.startDate = moment(fieldsValue.date[0]).format('YYYY-MM-DD HH:mm:ss');
      obj.endDate = moment(fieldsValue.date[1]).format('YYYY-MM-DD HH:mm:ss');
      if(moment(obj.startDate).isBefore(moment(obj.endDate).subtract(86399, 'second'))) {
        message.error('查询时间不能超过24小时');
        return;
      }
      obj.date = '';
      obj.pageRangeData = [];
      this.setState({
        loading: true,
        formValues: fieldsValue,
      });
      dispatch({
        type: 'vehicle/getVehicleInstrument',
        payload: obj,
        callback: (response) => {
          if (response) {
            if (response.code && response.code === '500') {
              message.error(response.description);
            }
            if (response.statusCode && response.statusCode !== '0') {
              message.error(response.statusMessage);
            }
            this.setState({
              list: response.data && response.data.list  ? response.data.list : [],
              pagination: response.data && response.data.pagination  ? response.data.pagination : '',
              pageRangeData:  response.data && response.data.pageRange  ? response.data.pageRange : [],
            })
          }
          this.setState({
            loading: false,
          })
        },
      });
    });
  };

  handleTableChange = (page) => {
    const { formValues, pageRangeData, pagination } = this.state;
    const { dispatch, vin } = this.props;
    let startDate = formValues && formValues.startDate ? formValues.startDate : `${moment().format('YYYY-MM-DD')} 00:00:00`;
    let endDate = formValues && formValues.endDate ? formValues.endDate: `${moment().format('YYYY-MM-DD')} 23:59:59`;
    const params = {
      page: page.current,
      size: 50,
      vin: vin,
      startDate,
      endDate,
      pageRangeData,
      total: pagination.total,
    };
    this.setState({
      loading: true,
    });
    dispatch({
      type: 'vehicle/getVehicleInstrument',
      payload: params,
      callback: (response) => {
        if (response) {
          if (response.code && response.code === '500') {
            message.error(response.description);
          }
          if (response.statusCode && response.statusCode !== '0') {
            message.error(response.statusMessage);
          }
          this.setState({
            list: response.data && response.data.list  ? response.data.list : [],
            pagination: response.data && response.data.pagination  ? response.data.pagination : '',
            pageRangeData:  response.data && response.data.pageRange  ? response.data.pageRange : [],
          })
        }
        this.setState({
          loading: false,
        })
      },
    });
  };

  handleExportExcel = ()=>{
    this.setState({expButtonLoading:true});
    const { form,vin } = this.props;
    form.validateFields((err, fieldsValue) => {
      const obj = fieldsValue;
      obj.vin = vin;
      obj.startDate = moment(fieldsValue.date[0]).format('YYYY-MM-DD HH:mm:ss');
      obj.endDate = moment(fieldsValue.date[1]).format('YYYY-MM-DD HH:mm:ss');
      if(moment(obj.startDate).isBefore(moment(obj.endDate).subtract(86399, 'second'))) {
        message.error('查询时间不能超过24小时');
        return;
      }

      const newOptions = {};
      newOptions.headers = {
        OptAuthorization: `bearer ${getToken()}`,
      };

      //构建Excel导出的列参数
      let params ='';
      this.state.checkedList.forEach(function(value){
        params += value +`,`
      });
      params = params.substring(0,params.length-1);
      const str = `/vehicle/getVehicleInstrumentExport?vin=`+ vin + `&startDate=` + obj.startDate +`&endDate=`+ obj.endDate +`&lines=`+ this.state.line_num +`&expire=`+ this.state.expire + `&param=` + params;
      this.props.dispatch({
        type: 'extendForm/queryGet',
        payload: {url: str},
        callback: (response) => {
          if (response.statusCode === '0') {
            window.location.href = response.data;
          } else {
            message.error(response.statusMessage);
          }
        },
      });
    });
  };




  renderSimpleForm() {
    const { getFieldDecorator } = this.props.form;
    const title = `导出记录上限`+this.state.line_num+`条，时间间隔`+this.state.expire/60+`分钟，确认导出？`;

    return (
      <Form style={{ marginBottom: 10 }} onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={12} sm={24}>
            <FormItem label="选择日期">
              {getFieldDecorator('date',{
                initialValue: [moment().startOf('day'), moment().endOf('day')],
                rules: [{ required: true, message: '请选择日期，间隔时间不能超过24小时' }],
              })(
                <RangePicker
                  // defaultValue={[moment(), moment()]}
                  placeholder={['开始时间', '结束时间']}
                  style={{ width: '100%' }}
                  format="YYYY-MM-DD HH:mm:ss"
                  showTime={{
                    hideDisabledOptions: true,
                    // defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('23:59:59', 'HH:mm:ss')],
                  }}
                  allowClear
                />
              )}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
              <span >
                <Button size='default' type='primary' htmlType='submit' onClick={this.handleSearch} >查询</Button>
                <Popconfirm title={title} onConfirm={this.handleExportExcel}>
                  <Button size='default' style={{ marginLeft: 20 }}>导出</Button>
                </Popconfirm>
              </span>
          </Col>
        </Row>
      </Form>
    );
  }

  checkboxChange = (checkedList) => {
    if(checkedList.length===0){
      message.warning('最少保留1项！',3);
      return;
    }else if(checkedList.length > parseInt(this.state.len)){
      message.warning('最多可选'+this.state.len+'项！',3);
      return;
    }

    this.setState({
      checkedList: checkedList,
    });
  };

  render() {
    const { list, pagination, loading,columns,plainOptions_code,plainOptions } = this.state;

    const fc = columns.filter(item => {
      return this.state.checkedList.includes(item.dataIndex);
    });

    const paginationProps = {
      showSizeChanger: true,
      defaultPageSize: 50,
      pageSizeOptions: ['50'],
      showQuickJumper: true,
      ...pagination,
      showTotal: () => <span>共&nbsp;{pagination === undefined ? 0 : pagination.total}&nbsp;条</span>,
    };

    return (
       <div>
          {this.renderSimpleForm()}
          <Collapse>
           <Panel header='可选择列(点击展开) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 最少保留1项，最多可选20项' key='1'>
             <div style={{ borderBottom: '1px solid #E9E9E9' }}>
               <CheckboxGroup value={this.state.checkedList} onChange={this.checkboxChange} style={{ width: '100%' }}
               >
                 <Row gutter={24}>
                   {
                     plainOptions_code.map((item,index) =>{
                       return (
                         <Col span={6} key={index}  style={{ marginBottom: 24 }}>
                           <Checkbox value={item}><Ellipsis length={10} tooltip>{plainOptions[index]}</Ellipsis></Checkbox>
                         </Col>
                       );
                     })
                   }
                 </Row>
               </CheckboxGroup>
             </div>
           </Panel>
          </Collapse>
          <Table
            bordered
            scroll= {{x: fc.length*150}}
            size="small"
            rowKey={record => record.createtime}
            columns={fc}
            dataSource={list}
            loading={loading}
            pagination={paginationProps}
            onChange={this.handleTableChange}
          />
       </div>
    );
  }
}
